<template>
    <rx-dialog @handOk="handleSubmit" @cancel="close" :oktext="$ti18('rxForm.okBtn','确定')" :canceltext="$ti18('rxForm.cancelBtn','取消')"   order="bottom">
        <div class="dialog">
            <!--            转移按钮-->
            <div class="dialog-circle" @click="moveToExportList">
                <i style="font-size: 18px;" class="iconfont iconxiangyou"/>
            </div>
            <!--        左边-->
            <div class="excel-dialog-le">
                <div class="dialog-all">{{i18n('entField','实体字段')}}</div>
                <div style="margin-top: 10px">
                    <a-checkbox  :checked="checkAll" @change="onCheckAllChange">
                        {{$ti18('rxList.selectAll','全选')}}
                    </a-checkbox>
                    <a-checkbox-group
                        style="width: 100%;"
                        v-model:value="checkedList"
                        @change="onChange"
                    >
                        <a-row>
                            <a-col :span="12" v-for="item of checkedBoxSource">
                                <a-checkbox :value="item.value">
                                    <div class="rx-checkbox-name" :title="item.label">{{ item.label }}</div>
                                </a-checkbox>
                            </a-col>
                        </a-row>
                    </a-checkbox-group>
                </div>
                <div class="dialog-all">{{i18n('standardField','标准字段')}}</div>
                <div style="margin-top: 10px">
                    <a-checkbox  :checked="standardAll" @change="onChStandardAll">
                        {{$ti18('rxList.selectAll','全选')}}
                    </a-checkbox>
                    <a-checkbox-group
                        v-model:value="standardId"
                        @change="onChangeStandard"
                    >
                        <a-row>
                            <a-col :span="12" v-for="item of standardList">
                                <a-checkbox :value="item.value">
                                    <div class="rx-checkbox-name" :title="item.label">{{ item.label }}</div>
                                </a-checkbox>
                            </a-col>
                        </a-row>
                    </a-checkbox-group>
                </div>
            </div>
            <div class="excel-dialog-center" style="padding-bottom: 0px">
                <div class="dialog-all">{{i18n('list.exportFields','要导出的字段')}}</div>
                <div class="excel-dialog-button">
                    <a-button size="small" type="danger" @click="removeRow">{{$ti18('rxList.delBtn','删除')}}</a-button>
                    <a-button size="small" type="primary" @click="upRow">{{i18n('list.upward','向上')}}</a-button>
                    <a-button size="small" type="primary" @click="downRow">{{i18n('list.down','向下')}}</a-button>
                    <a-button size="small" type="primary" @click="topRow">{{i18n('list.moveUp','上升一级')}}</a-button>
                    <a-button size="small" type="primary" @click="subRow">{{i18n('list.downOne','下降一级')}}</a-button>
                </div>
                <rx-grid ref="grid" :dataSource="headerFields" :allowRowSelect="true" :multiSelect="true"
                         :showPage="false" :bordered="true" :columns="headerColumns" id-field="field">
					<span slot="header" slot-scope="{text,record,index,blur}">
						<a-input v-model="record.header" @blur="blur(index,'header',text,record)" />
					</span>
                    <span v-if="showRender(record)" slot="showRender" slot-scope="{text,record,index}">
						<a-switch default-checked v-if="(record.renderType && record.renderType!='') "
                                  v-model="record.showRender" />
					</span>
                </rx-grid>
            </div>
        </div>
    </rx-dialog>
</template>

<script>
import {RxDialog,RxFit,Util} from "@lowcode/jpaas-common-lib";
import FormBoListApi from "@/api/form/core/formBoList";
import {cololumRenderTypeList} from "@/views/modules/form/core/js/CololumRenderTypes";

export default {
    name: "FormBoListExportExcelDialog",
    props: {
        row:{
            type:Object
        },
        boListKey: {
            type: String,
            default: ""
        },
        layerid: {
            type: String,
            default: ""
        },
        destroy: {
            type: Function
        }
    },
    computed: {
        grid() {
            return this.$refs.grid;
        }
    },
    components: {
        RxDialog,
        RxFit
    },
    data() {
        return {
            totalFields:[],
            headerFields: [],
            headerColumns: [{
                title: this.i18n('form.fieldName','字段名称'),
                dataIndex: 'header',
                allowCellEdit: true,
                scopedSlots: {
                    customRender: 'header'
                },
                width: 120
            },
                {
                    title: this.i18n('form.fieldKey','字段Key'),
                    dataIndex: 'field',
                    width: 120
                }
            ],
            haveRender: false,
            checkAll: false,
            checkedList: [],
            checkedBoxSource: [],
            standardAll: false,
            standardList: [],//标准字段
            standardId: [],//选中的标准字段ID
            exportId: "",
        }
    },
    created() {
        this.reloadColumns();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formBoListDialog", key);
        },
        handleSubmit(e){
            var fields=this.getExportFields();
            if(!fields || fields.length==0){
                this.$notification["warning"]({
                    message: this.$ti18('rxMsa.actionTips','操作提示'),
                    description: this.i18n('selLeftField','请从左边字段中选择需要导出的字段!'),
                });
                e.loading=false;
                return;
            }
            Util.closeWindow(this,"ok",JSON.stringify(fields));
        },
        cancel(){
            Util.closeWindow(this,"cancel");
        },
        getExportFields() {
            var fields = this.$refs.grid.getData();
            var list = [];
            for (var i = 0; i < fields.length; i++) {
                var field = fields[i];
                var tmp = this.handField(field);
                list.push(tmp);
            }
            return list;

        },
        handField(field) {
            var obj = {};
            obj.name = field.header;
            obj.key = field.field;
            obj.showRender = field.showRender;
            obj.renderType = field.renderType;
            var children = field.children;
            if (children && children.length > 0) {
                obj.children = [];
                for (var i = 0; i < children.length; i++) {
                    var tmp = children[i];
                    var cObj = this.handField(tmp);
                    obj.children.push(cObj);
                }
            }
            return obj;
        },
        reloadColumns() {
            var self_ = this;
            FormBoListApi.reloadColumnsByKey(this.boListKey,"false").then(res => {
                if (res.data) {
                    for (var obj of res.data) {
                        if (obj.renderType && obj.renderType!='COMMON') {
                            this.haveRender = true;
                            obj.showRender = true;
                        }else{
                            obj.showRender = false;
                        }
                    }
                }
                if (this.haveRender == true && this.headerColumns.length != 3) {
                    this.headerColumns.push({
                      title: this.i18n('form.showRender', '是否导出显示值'),
                      dataIndex: 'showRender',
                      scopedSlots: {
                        customRender: 'showRender'
                      },
                      width: 120
                    });
                }
                //把data存到totalFields里，在后续推到导出列的时候需要从这里拿，再只用header构建多选（因为如果存value,label这种双值格式会导致全选失效）（header相同会有问题）
                self_.totalFields = res.data;
                //重新加载前先清空数组，防止重复添加
                self_.checkedBoxSource = [];
                self_.standardList = [];
                for (let i = 0; i < self_.totalFields.length; i++) {
                    let header = self_.totalFields[i].header;
                    let field = self_.totalFields[i].field;
                    if (self_.totalFields[i].isCommonField) {
                        self_.standardList.push({label: header, value: field});
                    } else {
                        self_.checkedBoxSource.push({label: header, value: field});
                    }
                }
                self_.loadExport();
            });
        },
        loadExport() {
            if(!this.row || !this.row.setting){
                return;
            }
            var json = JSON.parse(this.row.setting);
            var fields = [];
            for (var i = 0; i < json.length; i++) {
                var field = json[i];
                var obj = this.handFieldTrun(field);
                //把导出时的配置从多选来源处删掉
                for (let i = 0; i < this.checkedBoxSource.length; i++) {
                    if (field.key == this.checkedBoxSource[i].value) {
                        this.checkedBoxSource.splice(i, 1);
                    }
                }
                for (let i = 0; i < this.standardList.length; i++) {
                    if (field.key == this.standardList[i].value) {
                        this.standardList.splice(i, 1);
                    }
                }
                fields.push(obj);
            }
            this.headerFields = fields;
        },
        handFieldTrun(field) {
            var obj = {};
            obj.header = field.name;
            obj.field = field.key;
            obj.showRender = field.showRender;
            obj.renderType = field.renderType;
            var children = field.children;
            if (children && children.length > 0) {
                obj.children = [];
                for (var i = 0; i < children.length; i++) {
                    var tmp = children[i];
                    var cObj = this.handFieldTrun(tmp);
                    obj.children.push(cObj);
                }
            }
            return obj;
        },
        addRow() {
            this.grid.addRow();
        },
        removeRow() {
            this.removeRowBoxSource();
            this.removeRowStandard()
            Object.assign(this, {
                checkAll: false,
                standardAll: false,
            });
            this.grid.removeRows();
        },
        removeRowBoxSource(){
            //删除行同时 多选框来源加回去
            var selectedRows = this.grid.getSelectedRows();
            for (let i = 0; i < selectedRows.length; i++) {
                //判断是否是原有字段中存在的，是，才需要放回左边
                var exists = false;
                for (let j = 0; j < this.totalFields.length; j++) {
                    if (!this.totalFields[j].isCommonField && this.totalFields[j].header == selectedRows[i].header) {
                        exists = true;
                        break;
                    }
                }
                //判断左边现有字段是否已存在该字段，若已存在则不添加
                var existBox = false;
                for (let boxSource of this.checkedBoxSource) {
                    if (boxSource == selectedRows[i].header) {
                        existBox = true
                        break
                    }
                }
                //为原有字段 且 左边不存在该字段 添加回左边
                if (exists && !existBox) {
                    this.checkedBoxSource.push({label: selectedRows[i].header, value: selectedRows[i].field});
                }
            }
        },
        removeRowStandard(){
            var selectedRows = this.grid.getSelectedRows();
            for (let i = 0; i < selectedRows.length; i++) {
                //判断是否是原有字段中存在的，是，才需要放回左边
                var exists = false;
                for (let j = 0; j < this.totalFields.length; j++) {
                    if (this.totalFields[j].isCommonField && this.totalFields[j].header == selectedRows[i].header) {
                        exists = true;
                        break;
                    }
                }
                //standardList
                let standard = false;
                for (let boxSource_ of this.standardList) {
                    if (boxSource_ == selectedRows[i].header) {
                        standard = true
                        break
                    }
                }
                //为原有字段 且 左边不存在该字段 添加回左边
                if (exists && !standard) {
                    this.standardList.push({label: selectedRows[i].header, value: selectedRows[i].field});
                }
            }
        },
        upRow() {
            this.grid.moveUp();
        },
        downRow() {
            this.grid.moveDown();
        },
        topRow() {
            this.grid.toMain();
        },
        subRow() {
            this.grid.toSub();
        },
        moveToExportList() {
            this.initCheckedList();
            this.initStandardList();
            Object.assign(this, {
                checkAll: false,
                standardAll: false,
            });

        },
        initCheckedList(){
            let list = JSON.parse(JSON.stringify(this.checkedBoxSource))
            this.checkedList.forEach(item=>{
                for (let i = 0; i <this.totalFields.length; i++) {
                    if (this.totalFields[i].field == item) {
                        this.headerFields.push(this.totalFields[i]);
                    }
                }
                for (let j = 0; j <list.length; j++) {
                    if (list[j].value == item) {
                        list.splice(j, 1);
                    }
                }
            })
            this.checkedList = [];
            this.checkedBoxSource = []
            let self = this;
            setTimeout(function(){
                self.checkedBoxSource = list
            },100)
        },
        initStandardList(){
            let list = JSON.parse(JSON.stringify(this.standardList))
            this.standardId.forEach(item=>{
                for (let i = 0; i < this.totalFields.length; i++) {
                    if (this.totalFields[i].field == item) {
                        this.headerFields.push(this.totalFields[i]);
                    }
                }
                for (let j = 0; j < list.length; j++) {
                    if (list[j].value == item) {
                        list.splice(j, 1);
                    }
                }
            })
            this.standardId = [];
            this.standardList = [];
            let self = this;
            setTimeout(function(){
                self.standardList = list
            },100)

        },
        onChange(checkedList) {
            //勾选时，做一个全选的按钮状态更新
            this.checkAll = checkedList.length === this.checkedBoxSource.length;
        },
        onChangeStandard(checkedList) {
            //勾选时，做一个全选的按钮状态更新
            this.standardAll = checkedList.length === this.standardList.length;
        },
        onCheckAllChange(e) {
            //全选操作
            Object.assign(this, {
                checkedList: e.target.checked ? this.checkedBoxSource.map(item=>{return item.value;}) : [],
                checkAll: e.target.checked,
            });
        },
        onChStandardAll(e) {
            Object.assign(this, {
                standardId: e.target.checked ? this.standardList.map(item => {
                    return item.value;
                }) : [],
                standardAll: e.target.checked,
            });
        },
        close(){
            Util.closeWindow(this,"cancel");
        },
        showRender(record){
            //未配置渲染
            if(!this.haveRender){
                return false;
            }
            for (let i = 0; i < cololumRenderTypeList.length; i++) {
                if(cololumRenderTypeList[i].value==record.renderType){
                    return cololumRenderTypeList[i].exportRender;
                }
            }
            return false;
        }
    }
}
</script>

<style scoped>
.dialog {
    display: flex;
    width: 100%;
    height: 100%;
    position: relative;
}

.dialog-circle {
    position: absolute;
    top: 119px;
    left: 380px;
    width: 40px;
    text-align: center;
    line-height: 40px;
    height: 40px;
    background-color: #ffffff;
    border: solid 1px #dadde0;
    border-radius: 50%;
    color: #46494d;
    z-index: 999;
}

.dialog-circle:hover {
    cursor: pointer;
    background-color: #1890ff;
    color: white;
}

.excel-dialog-le {
    overflow-y: auto;
    height: 100%;;
    width: 400px;
    padding: 20px;
    box-sizing: border-box;
    border-right: 1px solid #e8e8e8;
}
.dialog-all {
    border-left: 2px solid #1890ff;
    line-height: 13px;
    padding-left: 6px;
    font-weight: 500;
}
.rx-checkbox-name {
    display: block;
    width: 100px;
    overflow: hidden;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.excel-dialog-le>>>.ant-checkbox-wrapper{
    display: flex!important;
    cursor: pointer;
    height: 30px;
    align-items: center;
}
.excel-dialog-center {
    display: flex;
    flex-direction: column;
    flex: 1;
    border-right: 1px solid #e8e8e8;
    overflow: auto;
    padding: 20px;
    box-sizing: border-box;
}
.excel-dialog-button{
    margin: 10px 0px;
}
.excel-dialog-button button{
    margin-right: 5px;
}
</style>
